<template>
  <div class="introduction-form">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="真实名称" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="出生年月" prop="birday">
        <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.birday" style="width:100%">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="联系地址" prop="addr">
        <el-input v-model="ruleForm.addr"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email"></el-input>
      </el-form-item>
      <el-form-item label="学历" prop="experience">
        <el-input v-model="ruleForm.experience"></el-input>
      </el-form-item>
      <el-form-item label="图像" prop="imageUrl">
        <el-upload class="avatar-uploader" name='avatar' action="http://backServe.com:3000/user/uploader" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="ruleForm.imageUrl" :src="baseUrl+ruleForm.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">
          {{userItem?'编辑':'立即创建'}}
        </el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UserApi from '@/api/user';

export default {
  name: 'IntroductionForm',
  props: ['dialogVisible', 'userItem'],
  data() {
    return {
      baseUrl: 'http://backserve.com:3000',
      ruleForm: {
        userName: this.userItem ? this.userItem.user_name : '',
        birday: this.userItem ? this.userItem.birthday : '',
        phone: this.userItem ? this.userItem.phone : '',
        addr: this.userItem ? this.userItem.addr : '',
        email: this.userItem ? this.userItem.email : '',
        experience: this.userItem ? this.userItem.experience : '',
        imageUrl: this.userItem ? this.userItem.avatar_url : null,
      },
      rules: {
        userName: [
          { required: true, message: '请输入真实名称', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '长度在2到8个字符',
            trigger: 'blur',
          },
        ],
        birday: [{ required: true, message: '请输入生日', trigger: 'blur' }],
        phone: [
          {
            required: true,
            message: '请输入联系方式',
            trigger: 'blur',
          },
        ],
        addr: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
        experience: [
          { required: true, message: '请输入学历', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '长度在2到8个字符',
            trigger: 'blur',
          },
        ],
        imageUrl: [{ required: true, message: '请上传图片', trigger: 'blur' }],
      },
    };
  },
  methods: {
    // 图片上传成功
    handleAvatarSuccess(res) {
      if (res.data.length > 0) {
        const a = res.data[0];
        this.ruleForm.imageUrl = a;
      }
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      const isType = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isType && isLt2M;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.userItem) {
            this.ruleForm.birday = new Date(this.ruleForm.birday).getTime();
            this.ruleForm.id = this.userItem.id;
            UserApi.putUser(this.ruleForm)
              .then((data) => {
                if (data.data) {
                  this.$message({
                    message: data.message,
                    type: 'success',
                  });
                  this.resetForm('ruleForm');
                  this.$emit('update:dialogVisible', false);
                } else {
                  this.resetForm('ruleForm');
                  this.$emit('update:dialogVisible', false);
                  this.$message({
                    message: `${data.message}`,
                    type: 'error',
                  });
                }
              })
              .catch((err) => {
                this.$message({
                  message: `${err.message}`,
                  type: 'error',
                });
              });
          } else {
            this.ruleForm.birday = new Date(this.ruleForm.birday).getTime();
            UserApi.userInfo(this.ruleForm)
              .then((data) => {
                if (data.data) {
                  this.$message({
                    message: data.message,
                    type: 'success',
                  });
                  this.resetForm('ruleForm');
                  this.$emit('update:dialogVisible', false);
                } else {
                  this.$message({
                    message: data.message,
                    type: 'error',
                  });
                }
              })
              .catch((err) => {
                this.$message({
                  message: err.message,
                  type: 'error',
                });
              });
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  watch: {
    userItem() {
      if (this.userItem) {
        this.ruleForm.userName = this.userItem.user_name;
        this.ruleForm.birday = this.userItem.birthday;
        this.ruleForm.phone = this.userItem.phone;
        this.ruleForm.addr = this.userItem.addr;
        this.ruleForm.email = this.userItem.email;
        this.ruleForm.experience = this.userItem.experience;
        this.ruleForm.imageUrl = this.userItem.avatar_url;
      } else {
        this.ruleForm.userName = '';
        this.ruleForm.birday = '';
        this.ruleForm.phone = '';
        this.ruleForm.addr = '';
        this.ruleForm.email = '';
        this.ruleForm.experience = '';
        this.ruleForm.imageUrl = null;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.introduction-form {
  width: 100%;
  height: auto;
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
}
</style>
